﻿using System;
using System.Collections;
using UnityEngine;

public class AppUI : MonoBehaviour
{
    public Type preUI;
    public string preUIName => preUI.ToString();
    public Type nextUI;
    public UIController UIController => GetComponentInParent<UIController>();

    CanvasGroup m_CanvasGroup;
    public CanvasGroup canvasGroup
    {
        get
        {
            if (m_CanvasGroup == null)
                m_CanvasGroup = gameObject.AddComponent<CanvasGroup>();
            return m_CanvasGroup;
        }
    }
    public float fadeInAnimTime = 0.2f;
    public float fadeOutTime = 0.1f;
    public virtual void Awake()
    {

    }
    public virtual void Start()
    {

    }

    public virtual void DoOnActive()
    {

    }

    public virtual void DoOnDisactive()
    {

    }

    internal void PlayShowAnim(Action onEnd)
    {
        if (fadeInAnimTime <= 0)
        {
            onEnd?.Invoke();
        }
        else
        {
            canvasGroup.alpha = 0;
            StartCoroutine(IECanvasGroupAlpha(1, fadeOutTime));
            DoActionDelay.DelayAction(fadeOutTime, () =>
            {
                canvasGroup.alpha = 1;
                onEnd?.Invoke();
            });
        }
    }

    internal void PlayHideAnim(Action onEnd)
    {
        if (fadeOutTime <= 0)
        {
            onEnd?.Invoke();
        }
        else
        {
            canvasGroup.alpha = 1;
            StartCoroutine(IECanvasGroupAlpha(0, fadeOutTime));
            DoActionDelay.DelayAction(fadeOutTime, () =>
            {
                canvasGroup.alpha = 0;
                onEnd?.Invoke();
            });
        }
    }
    IEnumerator IECanvasGroupAlpha(float targetAlpha,float time)
    {
        float timer = 0;
        float originAlpha = canvasGroup.alpha;
        while(timer < time)
        {
            this.canvasGroup.alpha = Mathf.Lerp(originAlpha, targetAlpha, timer / time);

            timer += Time.deltaTime;
            yield return 0;
        }
        canvasGroup.alpha = targetAlpha;
    }

    public /*virtual*/ void GoBack()
    {
        //this.preUI = null;
        if (preUI == null)
            UIController.ShowUI(UIController.defaultPanel.GetType());
        else
            UIController.ShowUI(preUI);
    }

}
